
import {WSS_SERVER_URL} from '../config.js'
import store from "@/store/index.js"
import utils from '@/common/util.js'

let WebSocket={};
let id='',
    Token='',
	heartbeatInterval = null;    //检测连接;

// {"type":"bind","uid":1001}

let time=60*60*1000;

WebSocket.socketOpen = false;
WebSocket.socketMsgQueue = [];

// 判断socket是否已连接
WebSocket.checkSocketState=()=> {	
	let _this = this;
	
	uni.sendSocketMessage({
		data: 'open',
		success: (res) => {   
			WebSocket.socketOpen=true;
			return;
		},
		fail: (err) => { // 未连接打开websocket连接	 
			WebSocket.socketOpen=false; 
			WebSocket.open(id,Token);
			// if(!WebSocket.socketOpen){
			// 	WebSocket.open(); 
			// }
		}
	});
}, 

// 建立连接
WebSocket.open=()=>{  
	if(uni.getStorageSync('userInfo')){
		id=uni.getStorageSync('userInfo').id;
	} 
	if(uni.getStorageSync('token')){
		Token=uni.getStorageSync('token');
	}
	uni.connectSocket({
		url: WSS_SERVER_URL+'?from=app&token='+Token,
		success: (res) => {  
			console.log('链接成功')
		}
	});
	uni.onSocketOpen ((res)=> {  
		console.log(res+'打开成功')	
				
		WebSocket.start();
		WebSocket.socketOpen = true; 	 
		WebSocket.sendSocketMessage('{"type":"bind","from":"app","uid":"'+id+'"}')
		
	});
	uni.onSocketError ((res)=>{ 
		console.log(res+'打开失败') 
		// uni.showToast({
		// 	title:'网络连接异常',
		// 	mask:true
		// })
		WebSocket.socketOpen = false; 
		// let reset_num=5;
		// WebSocket.checkSocketState();
	});
	
	WebSocket.onSocketMessage();

},

// 发送数据
WebSocket.sendSocketMessage=(msg)=> {    
	if(WebSocket.socketOpen) {
		uni.sendSocketMessage({
		  data: msg,
		  success(res) { 
		  },
		  fail(err) {
		  	console.log('端口链接',err) 
			WebSocket.socketOpen=false;
			WebSocket.open();
		  }
		  
		});
	}else{
		console.log('发送失败') 
		WebSocket.open();
		WebSocket.socketMsgQueue.push(msg);
	}
},

WebSocket.onSocketMessage=()=>{ 
	uni.onSocketMessage((res)=>{    
		store.dispatch('new_socket_data', JSON.parse(res.data))
	}); 
},

// 重连
WebSocket.reConnect=()=> {
    let timer=60*60*1000; 
    timer = setTimeout(() => {
		WebSocket.socketOpen=false;
    },time)
}

//开启链接检测
WebSocket.start = () => {  
	clearInterval(heartbeatInterval);
	heartbeatInterval=null;
	heartbeatInterval=setInterval(() => {
		WebSocket.sendSocketMessage('{"type":"bind","from":"app","uid":"'+id+'}')
	}, 30000)	
}
  
WebSocket.close=()=>{
	uni.closeSocket({
		code:1000,  
		reason:'App Hide'  
	}) 
	clearInterval(heartbeatInterval);
	heartbeatInterval=null;
}



export default WebSocket